#include <iostream>
#include <vector>
#include <string>
#include <functional>
#include <unistd.h>
#include <pthread.h>

using namespace std;

// 一把锁会不会有死锁问题呢？
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

int cnt = 100;

using namespace std;

void *startRoutine(void *args)
{
    string name = static_cast<char *>(args);
    while (true)
    {
        pthread_mutex_lock(&mutex);
        cout << name << " count : " << cnt-- << endl;

        // 代码写错了，写了两个锁
        // pthread_mutex_lock(&mutex);
        pthread_mutex_unlock(&mutex);
        
        // 耗时的操作尽量不要再临界区里面
        sleep(1);
    }
}

int main()
{
    pthread_t t1;
    pthread_create(&t1, nullptr, startRoutine, (void *)"thread 1");
    pthread_t t2;
    pthread_create(&t2, nullptr, startRoutine, (void *)"thread 2");

    pthread_join(t1, nullptr);
    pthread_join(t2, nullptr);

    return 0;
}
